package com.alennus.blog.service;

import com.alennus.blog.domain.Role;
import com.alennus.blog.domain.RoleMenu;
import com.alennus.blog.repository.RoleRepository;
import com.alennus.blog.utils.DateUtils;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by pactera on 2018/5/23.
 */
@Service
public class RoleService {

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    MongoTemplate template;

    public Page<Role> findRoles(Role role, Pageable pageable){
        Criteria criteria = new Criteria();
//        if(!StringUtils.isEmpty(menu.getParentId())){
//            criteria.and("parentId").is(menu.getParentId());
//        }
        Query query = new Query(criteria);
        //查询
        List<Role> list = template.find(query.with(pageable), Role.class);
        Long count =  template.count(query, Role.class);
        //将集合与分页结果封装
        return new PageImpl<>(list, pageable, count);
    }

    @Transactional
    public Role saveOrUpdate(Role role){
        List<String> menuIds = role.getRoleMenus();
        List<RoleMenu> roleMenuList = Lists.newArrayList();
       for(String menuId:menuIds){
            RoleMenu roleMenu = new RoleMenu();
           roleMenu.setRoleId(role.getId());
           roleMenu.setMenuId(menuId);
           roleMenu.setCreatedDate(DateUtils.getCurrentDatetime());
           roleMenu.setUpdateDate(DateUtils.getCurrentDatetime());
           roleMenuList.add(roleMenu);
       }
        roleMenuService.deleteByRoleId(role.getId());
        roleMenuService.saveAll(roleMenuList);
        return roleRepository.save(role);
    }

    public void delete(List<Role> roles){
        roleRepository.deleteAll(roles);
    }

    public Role findById(String id){
        return roleRepository.findById(id).get();
    }
}
